from iClouds.allSerializers import *
from django_redis import get_redis_connection
from .Serializers import *
from rest_framework.decorators import action
from . import tasks as TASK
import time, json
from qiniu import Auth


# Create your views here.
class UserPassLoginViewSet(viewsets.ModelViewSet):
    __title__ = "用户登录"
    __group__ = "文件模块"
    __info__ = {
        "get": "文件列表",
        "post": "用户登录",
        "patch": "编辑景点",
        "delete": "移除景点",
    }
    __doc__ = """	list:
    <h4>文件列表</h4>
    retrieve:
    <h4>文件详情</h4>
    create:
    <h4>用户登录</h4>
        username:用户名|手机号|邮箱
        password:密码.md5()
        返回： {token}
        请求头: headers = {Authorization: token}
    partial_update:
    <h4>景点编辑</h4>
    delete:
    partial_update:
    <h4>景点编辑</h4>
    delete:
    <h4>景点移除</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = UserPassLoginSerializer
    queryset = AllinpayUserUserList.objects.all().order_by("id")

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response({"rescode": 200, "resmsg": serializer.data})


class UserInfoLoginViewSet(viewsets.ModelViewSet):
    __title__ = "用户信息"
    __group__ = "文件模块"
    __info__ = {
        "get": "文件列表",
        "post": "用户信息",
        "patch": "编辑景点",
        "delete": "移除景点",
    }
    __doc__ = """	list:
    <h4>文件列表</h4>
    retrieve:
    <h4>文件详情</h4>
    create:
    <h4>用户信息</h4>
    partial_update:
    <h4>景点编辑</h4>
    delete:
    partial_update:
    <h4>景点编辑</h4>
    delete:
    <h4>景点移除</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = AllinpayWxchatList.objects.all().order_by("id")

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        try:
            queryset = self.filter_queryset(self.get_queryset().get(userid=answer))
            serializer = ModelAllinpayWxchatListSerializer(queryset)
        except BaseException as err:
            raise NotFound("未找到该用户信息")
        else:
            return Response({"rescode": 200, "resmsg": serializer.data})


class HasQiniuUpTokenViewSet(viewsets.ModelViewSet):
    __title__ = "请求七牛上传凭证"
    __group__ = "文件模块"
    __info__ = {
        "get": "文件列表",
        "post": "请求七牛上传凭证",
        "patch": "编辑景点",
        "delete": "移除景点",
    }
    __doc__ = """	list:
    <h4>文件列表</h4>
    retrieve:
    <h4>文件详情</h4>
    create:
    <h4>请求七牛上传凭证</h4>
    partial_update:
    <h4>景点编辑</h4>
    delete:
    partial_update:
    <h4>景点编辑</h4>
    delete:
    <h4>景点移除</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        access_key = "EjQy0QGvHw7DWKwL5ZD9DrhcZWWkXv7P9eYZ8VKz"
        secret_key = "NoFBsyVXMtH1Eq63F5O9jg1KjjqlZ1nT7xfKSJXb"
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = "3vppt"
        # 上传后保存的文件名
        key = None
        # 生成上传 Token，可以指定过期时间等
        # 上传策略示例
        # https://developer.qiniu.com/kodo/manual/1206/put-policy
        # https://developer.qiniu.com/kodo/1206/put-policy
        policy = {
            # 'callbackUrl':'https://requestb.in/1c7q2d31',
            # 'callbackBody':'filename=$(fname)&filesize=$(fsize)'
            # 'persistentOps':'ppt_media',
            "forceSaveKey": True,
            "saveKey": "ppt_media/$(etag)&$(fname)",
            "returnUrl": None,
            "returnBody": json.dumps(
                {"key": "$(key)", "hash": "$(etag)", "fname": "$(fname)"}
            ),
        }
        # 3600为token过期时间，秒为单位。3600等于一小时
        # ppt_media
        # https://oss.3vppt.com/ppt_media/Fh6LNpKJu3uZpFYnJv72AmJTPUWI%26map.png
        token = q.upload_token(bucket_name, key, 3600, policy)
        return Response({"uptoken": token})


class QiniuUploadListModelViewSet(viewsets.ModelViewSet):
    __title__ = "七牛文件存储"
    __group__ = "文件模块"
    __info__ = {"post": "七牛文件存储"}
    __doc__ = """	
    create:
    <h4>七牛文件存储</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = QiniuUploadListSerializer
    queryset = AllinpayUploadList.objects.all().order_by("id")

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer, creattime=timezone.now())
        return Response({"rescode": 200, "resmsg": "seccess"})


class FileUploadListModelViewSet(viewsets.ModelViewSet):
    __title__ = "七牛文件列表"
    __group__ = "文件模块"
    __info__ = {
        "get": "文件列表",
        "post": "文件上传",
        "patch": "编辑文件",
        "delete": "移除文件",
    }
    __doc__ = """	list:
    <h4>文件列表</h4>
        查询文件列表
    retrieve:
    <h4>文件详情</h4>
        根据ID查询记录详情
    create:
    <h4>文件上传</h4>        
    partial_update:
    <h4>文件编辑</h4>
        根据ID编辑字段属性
    delete:
    <h4>景点移除</h4>"""
    http_method_names = ["get", "patch"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = AllinpayUploadListSerializer
    queryset = AllinpayUploadList.objects.all().order_by("id")

    # filterset_class = CallmeListFilterSet
    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_fields = ["answer", "sorth"]
    search_fields = ["name", "creattime", "filename"]
    ordering_fields = ["id"]

    pagination_class = LargePagination

    def list(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        queryset = self.filter_queryset(self.get_queryset().filter(answer=answer))
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        # 是否验证参数完整性 False:验证， True:不验证
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


# =========================================================================


class LocalFileUploadListModelViewSet(viewsets.ModelViewSet):
    __title__ = "本地文件上传"
    __group__ = "文件模块"
    __info__ = {
        "get": "文件列表",
        "post": "文件上传",
        "patch": "编辑景点",
        "delete": "移除景点",
    }
    __doc__ = """	list:
    <h4>文件列表</h4>
    retrieve:
    <h4>文件详情</h4>
    create:
    <h4>文件上传</h4>
        Content-Type: multipart/form-data;
    partial_update:
    <h4>景点编辑</h4>
    delete:
    <h4>景点移除</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = AllinpayUploadListSerializer
    queryset = AllinpayUploadList.objects.all().order_by("id")

    # filterset_class = CallmeListFilterSet
    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_fields = ["answer", "sorth"]
    search_fields = ["name", "creattime", "filename"]
    ordering_fields = ["id"]

    pagination_class = LargePagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        db = serializer.data.copy()
        # serializer.save()
        images = request.FILES
        if not images:
            raise MyBaseError("查找资源失败")
        # 创建资源目录
        sort = time.strftime("%Y%m%d", time.localtime())
        if not os.path.exists(settings.MEDIA_ROOT / sort):
            os.mkdir(settings.MEDIA_ROOT / sort)
        res = []
        for f in images.getlist("file"):
            # 原始文件名
            db["filename"] = f.name
            # 取扩展名
            exc = os.path.splitext(f.name)[1]
            # 取随机名
            allname = f"{int(time.time())}{has_chocode(3)}{exc}"
            # 保存文件
            f._set_name(allname)
            with open(settings.MEDIA_ROOT / f"{sort}/{allname}", "wb") as fs:
                for chunk in f.chunks():
                    fs.write(chunk)
            # 记录地址
            db["header"] = f"/static/upload/{sort}/{allname}"
            db["creattime"] = timezone.now()
            db["answer"] = ""
            res.append(db)
            # save
            AllinpayUploadList(**db).save()
        return Response({"rescode": 200, "resmsg": res})


class HasWechatCodeLoginViewSet(viewsets.ModelViewSet):
    __title__ = "请求登录二维码"
    __group__ = "文件模块"
    __info__ = {
        "get": "文件列表",
        "post": "文件上传",
        "patch": "编辑景点",
        "delete": "移除景点",
    }
    __doc__ = """	
    list:
    <h4>文件列表</h4>
    retrieve:
    <h4>文件详情</h4>
    create:
    <h4>请求登录二维码</h4>  
        `Top: `该接口为异步请求，请根据返回的`Task_id`轮训请求结果   
    partial_update:
    <h4>景点编辑</h4>
    delete:
    <h4>景点移除</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    # queryset = FileUploadList.objects.all().order_by("id")

    # filterset_class = CallmeListFilterSet
    # filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_fields = ["answer", "sorth"]
    # search_fields = ["name", "creattime", "filename"]
    # ordering_fields = ["id"]

    # pagination_class = LargePagination

    def create(self, request, *args, **kwargs):
        # serializer = self.serializer_class(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # res = TASK.requestCode.delay()
        return Response({"rescode": 200, "resmsg": {"Task_ID": ""}})


# ==========================================================================


class YlWxCourseViewSet(viewsets.ModelViewSet):
    __title__ = "报名价签"
    __group__ = "报名组件"
    __info__ = {
        "get": "查询报名价签列表",
        "post": "创建报名价签",
        "put": "编辑报名价签",
        "patch": "编辑报名价签",
        "delete": "移除报名价签",
    }
    __doc__ = """	
    list:
    <h4>报名价签列表</h4>
    retrieve:
    <h4>报名价签详情</h4>
    create:
    <h4>创建报名价签</h4>
    update:
    <h4>编辑报名价签</h4>
    partial_update:
    <h4>编辑报名价签</h4>
    delete:
    <h4>移除报名价签</h4>"""
    http_method_names = ["get", "post", "put"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = YlWxCourseSerializer
    queryset = YlWxCourse.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["parent"]
    search_fields = ["name"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return YlWxCourseSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class YlWxPlatformCourseViewSet(viewsets.ModelViewSet):
    __title__ = "活动名称"
    __group__ = "报名组件"
    __info__ = {
        "get": "查询活动名称列表",
        "post": "创建活动名称",
        "put": "编辑活动名称",
        "patch": "编辑活动名称",
        "delete": "移除活动名称",
    }
    __doc__ = """	
    list:
    <h4>活动名称列表</h4>
    retrieve:
    <h4>活动名称详情</h4>
    create:
    <h4>活动名称基本</h4>
    update:
    <h4>编辑活动名称</h4>
    partial_update:
    <h4>编辑活动名称</h4>
    delete:
    <h4>移除活动名称</h4>"""
    http_method_names = ["get", "post", "put"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = YlWxPlatformCourseSerializer
    queryset = YlWxPlatformCourse.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["parent"]
    search_fields = ["name"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return YlWxPlatformCourseSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class YlWxSchoolGroupViewSet(viewsets.ModelViewSet):
    __title__ = "单位场所名称"
    __group__ = "报名组件"
    __info__ = {
        "get": "查询单位场所名称列表",
        "post": "创建单位场所名称",
        "put": "编辑单位场所名称",
        "patch": "编辑单位场所名称",
        "delete": "移除单位场所名称",
    }
    __doc__ = """	
    list:
    <h4>单位场所名称列表</h4>
    retrieve:
    <h4>单位场所名称详情</h4>
    create:
    <h4>创建单位场所名称</h4>
    update:
    <h4>编辑单位场所名称</h4>
    partial_update:
    <h4>编辑单位场所名称</h4>
    delete:
    <h4>移除单位场所名称</h4>"""
    http_method_names = ["get", "post", "put"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = YlWxSchoolGroupSerializer
    queryset = YlWxSchoolGroup.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["pid"]
    search_fields = ["name"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return YlWxSchoolGroupSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


# ==============================================================================
# 名画也疯狂主题
# ==============================================================================
class postAniPortraitViewSet(viewsets.ModelViewSet):
    __title__ = "模板列表"
    __group__ = "名画系列"
    __info__ = {
        "get": "查询模板列表",
        "post": "创建动画",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "视频上墙",
    }
    __doc__ = """	
    list:
    <h4>查询模板列表</h4>
        ai服务器上传模板 
        http://{AI服务器}:{web端口}/media/models/{finename}       
    retrieve:
    <h4>查询AI服务器信息</h4> 
        id = 1 # 服务器信息
    create:
    <h4>模板列表</h4>
        http://lease.3vppt.com/media/{path}/{filename}
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>视频上墙</h4>
        /{id}/ = 视频ID
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    # authentication_classes = [UsersJWTAuthentication]
    # permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        root = settings.MEDIA_ROOT / "models"
        r = [p for p in os.listdir(root) if os.path.isfile(os.path.join(root, p))]
        root = settings.MEDIA_ROOT / "music"
        m = [p for p in os.listdir(root) if os.path.isfile(os.path.join(root, p))]
        root = settings.MEDIA_ROOT / "lcr"
        l = [p for p in os.listdir(root) if os.path.isfile(os.path.join(root, p))]
        return Response({"rescode": 200, "resmsg": {"models": r, "music": m, "lcr": l}})


class postAniPortraitTowViewSet(viewsets.ModelViewSet):
    __title__ = "请求创建动画"
    __group__ = "名画系列"
    __info__ = {
        "get": "查询模板列表",
        "post": "创建动画",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>查询模板列表</h4>
    http://lease.3vppt.com/media/{path}/{filename}
    retrieve:
    <h4>查询模板详情</h4>
    `禁用`
    create:
    <h4>创建动画</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [] if settings.DEBUG else [UsersJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [MyPermissions]
    serializer_class = postAniPortraitSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        r = serializer.data
        r["answer"] = answer
        rds = get_redis_connection("sysconf")
        rds.rpush("aniPortrait", f"{r}")
        # rds.expire("aniPortrait", 300)
        count = rds.llen("aniPortrait")

        return Response({"rescode": 200, "resmsg": count})


class playAniPortraitViewSet(viewsets.ModelViewSet):
    __title__ = "视频上墙"
    __group__ = "名画系列"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "视频上墙",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>视频上墙</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = playAniPortraitSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        uid = serializer.data.get("screen")
        vid = serializer.data.get("vid")

        try:
            r = AllinpayUploadList.objects.get(id=vid)

        except BaseException as err:
            return Response({"rescode": 400, "resmsg": "视频文件不存在"})
        try:
            openid = AllinpayWxchatList.objects.get(userid=r.answer).openid
            face = YlWxMember.objects.get(openid=openid).head_img
        except BaseException as err:
            face = None
        rds = get_redis_connection("sysconf")
        rds.rpush(f"screen_{uid}", f"[{r.filename},{r.header},{face}]")
        rds.expire(f"screen_{uid}", 300)

        return Response({"rescode": 200, "resmsg": "success"})


class listAniPortraitViewSet(viewsets.ModelViewSet):
    __title__ = "大屏播放列表"
    __group__ = "名画系列"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "大屏播放列表",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>大屏播放列表</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = listAniPortraitSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        uid = serializer.data.get("screen")
        rds = get_redis_connection("sysconf")
        res = rds.blpop(f"screen_{uid}", 1)
        return Response({"rescode": 200, "resmsg": res})


class taskAniPortraitViewSet(viewsets.ModelViewSet):
    __title__ = "获取合成任务"
    __group__ = "名画系列"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "获取合成任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>获取合成任务</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        # serializer = self.serializer_class(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # print(dir(request))
        # print(request.META)
        # print("参数:", request.META.get("HTTP_NAME"))
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise MyBaseError("请求失败")
        rds = get_redis_connection("sysconf")
        res = rds.blpop("aniPortrait", 1)
        if not res:
            raise MyBaseError("没有发现任务")
        r = eval(res[1])
        r["ref_img"] = (
            f'http://192.168.31.211:8000/media/models/{r["ref_img"]}'
            if settings.DEBUG
            else f'http://lease.3vppt.com/media/models/{r["ref_img"]}'
        )
        # r["source_video"] = f'http://oss.3vppt.com/{r["source_video"]}'
        return Response({"rescode": 200, "resmsg": r})


class QiniuForAniPortModelViewSet(viewsets.ModelViewSet):
    __title__ = "七牛文件存储"
    __group__ = "文件模块"
    __info__ = {"post": "七牛文件存储"}
    __doc__ = """	
    create:
    <h4>七牛文件存储</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = QiniuUploadListSerializer
    queryset = AllinpayUploadList.objects.all().order_by("id")

    def create(self, request, *args, **kwargs):
        # print(request.META.get("CLIENT_NAME"))
        # answer = request.user.id if request.user else 1
        answer = request.META.get("HTTP_NAME")
        if not answer:
            raise MyBaseError("请求失败")
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer, creattime=timezone.now())
        return Response({"rescode": 200, "resmsg": "seccess"})


class AllinpayUserPowerViewSet(viewsets.ModelViewSet):
    __title__ = "用户多媒体资源"
    __group__ = "文件模块"
    __info__ = {
        "get": "查询用户多媒体资源列表",
        "post": "创建用户多媒体资源",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除用户多媒体资源",
    }
    __doc__ = """	
    list:
    <h4>用户多媒体资源列表</h4>
    retrieve:
    <h4>用户多媒体资源详情</h4>
    create:
    <h4>创建用户多媒体资源</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除用户多媒体资源</h4>"""
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [] if settings.DEBUG else [UsersJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [UserPermissions]
    serializer_class = AllinpayUserPowerSerializer
    queryset = AllinpayUserPower.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["answer", "form"]
    # search_fields = ['phone','email']
    # ordering_fields = 'id'

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer, current=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        # print(answer, type(answer))
        # print(instance.answer, type(instance.answer))
        if not instance.answer == answer:
            raise ValidationError("没有权限")
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# 检查视图
filter_views(globals())
